package cn.kgc.service.impl;

import cn.kgc.dao.AccountDao;
import cn.kgc.pojo.Account;
import cn.kgc.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;
    /**
     * 根据账号查询账户
     *
     * @param accountNum
     */
    public Account findAccountByNum(String accountNum) throws SQLException {
        return accountDao.getAccountByNum(accountNum);
    }

    /**
     * 更新账户
     *
     * @param account
     */
    public Integer modifyAccount(Account account) throws SQLException {
        return accountDao.updateAccount(account);
    }

    /**
     * 模拟转账，如果转出金额大于账户余额则设定报一个异常
     */
    public void transfer(String sourceNum, String desNum, Float money) throws SQLException {
        //根据账号查询两个账户
        Account sourceAccount=accountDao.getAccountByNum(sourceNum);
        Account desAccount=accountDao.getAccountByNum(desNum);
        if (sourceAccount.getAccountMoney()< money){
            System.out.println("转账失败，余额不足！");
            int i = 1/0;
          }
        // 修改两个账户的余额
        sourceAccount.setAccountMoney(sourceAccount.getAccountMoney()-money);
        desAccount.setAccountMoney(desAccount.getAccountMoney()+money);
        //将数据持久化到数据库中
        accountDao.updateAccount(sourceAccount);
        accountDao.updateAccount(desAccount);
    }
}
